import { CTCE_TOKEN } from '../config/storageTypes'
import { getCache, removeCache, setCache } from './storageUtils'

export const CONTENT_TYPE_JSON = 'application/json'
export const CONTENT_TYPE_FORM = 'application/x-www-form-urlencoded'

// 网络错误
export const NETWORK_ERROR = 1
// 网络超时
export const NETWORK_TIMEOUT = 2
// 网络返回数据格式化一次
export const NETWORK_JSON_EXCEPTION = 3

export const SUCCESS = 200

class HttpManager {

    constructor() {
        this.optionParams = {
            timeoutMs: 15000,
            token: null,
            authorizationCode: null
        };
    };

    async getFetch(url, header, type) {
        return this.netFetch(url, 'GET', null, null, header, type)
    }

    async netFetch(url, method = 'GET', params, json, header, type) {
        //let isConnected = await NetInfo.isConnected.fetch().done;
        let isConnected = true
        if (!isConnected) {
            return {
                /*result: false,
                code: Code.NETWORK_ERROR,
                msg: I18n('netError')*/
            }
        }

        let headers = {}
        if (header) {
            headers = Object.assign({}, headers, header)
        }

        // 授权码
        if (!this.optionParams.authorizationCode) {
            let authorizationCode = await this.getAuthorization()
            if (authorizationCode) {
                this.optionParams.authorizationCode = authorizationCode
            }
        }

        let requestParams

        headers.key = this.optionParams.authorizationCode

        if (method !== 'GET') {
            if (json) {
                requestParams = this.formParamsJson(method, params, headers)
            } else {
                requestParams = this.formParams(method, params, headers)
            }
        } else {
            requestParams = {
                method: 'GET',
                headers: headers,
                body: params
            }
        }

        let response = await this.requestWithTimeout(this.optionParams.timeoutMs, this.fetch(url, requestParams, type))

        return response
    }


    clearAuthorization() {
        this.optionParams.authorizationCode = null
        removeCache(CTCE_TOKEN)
    }

    async getAuthorization() {
        let token = await getCache(CTCE_TOKEN)
        if (!token) {
            // let basic = await getCache(USER_BASIC_CODE);
            // if (!basic) {
            //     //提示输入账号密码
            // } else {
            //     //通过 basic 去获取token，获取到设置，返回token
            //     return `Basic ${basic}`;
            // }
        } else {
            this.optionParams.authorizationCode = token
            return token
        }

    }

    formParamsJson(method, params, headers) {
        const body = JSON.stringify(params)
        const req = {
            method: method,
            headers: {
                'Content-Type': CONTENT_TYPE_JSON,
                ...(headers || {})
            },
            body
        }
        return req
    }


    formParams(method, params, headers) {
        const str = []
        for (let p in params) {
            str.push((p) + '=' + (params[p]))
        }
        let body = null
        if (str.length > 0) {
            body = str.join('&')
        }
        const req = {
            method: method,
            headers: {
                'Content-Type': CONTENT_TYPE_FORM,
                ...(headers || {})
            },
            body
        }
        return req
    }

    requestWithTimeout(ms, promise) {
        return new Promise((resolve, reject) => {
            const timeoutId = setTimeout(() => {
                resolve({
                    status: NETWORK_TIMEOUT,
                    message: ''
                })
            }, ms)
            promise.then(
                (res) => {
                    clearTimeout(timeoutId)
                    resolve(res)
                },
                (err) => {
                    clearTimeout(timeoutId)
                    resolve(err)
                }
            );
        })
    }

    fetch(path, requestParams, type = 'json') {
        const axios = weex.requireModule('bmAxios')
        return new Promise((resolve, reject) => {
            axios.fetch({
                method: requestParams.method,
                url: path,
                header: requestParams.headers,
                data: requestParams.body,
                timeout: 15000
            }, resData => {
                resolve(resData)
            })
        })

    }
}

export default new HttpManager()
